import Popup from './src/Popup.vue'
import Dialog from './src/Dialog.vue'
import Drawer from './src/Drawer.vue'
import Card from './src/Card.vue'
import { createVNode, VNode, render, h } from 'vue'
import { ElButton } from 'element-plus'

export { Popup, Dialog, Drawer, Card }
type PopupSlots = { default: (...args) => VNode, title?: (...args) => VNode, footer?: (...args) => VNode }
export const closePopupKey = Symbol('closePopup')

export function open(popupProps: Record<string, any>, component, componentProps?: Record<string, any>) {
  popup(popupProps, {default: () => h(component, componentProps)})
}

export function popup(popupProps: Record<string, any>, popupSlots: PopupSlots) {
  const body = document.body
  const container = document.createElement('div')
  const onClose = () => body.removeChild(container)
  body.appendChild(container)

  const position = popupProps?.position == 'drawer' ? 'drawer' : 'dialog'
  popupProps = { ...(popupProps || {}), position, onClose, visible: true }
  const vnode = createVNode(Popup, popupProps, popupSlots)
  render(vnode, container)
}

export function footer(callback: () => void) {
  return ({ close }) => {
    async function ok() {
      await callback()
      close()
    }

    return h('div', {class: 'flex-center'}, [
      h(ElButton, {type: 'primary', onClick: ok}, () => '确定'),
      h(ElButton, {onClick: close}, () => '关闭')
    ])
  }
}
